package day10;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.junit.Test;

public class ReflectDemo {

	@Test
	public void testClass() throws ClassNotFoundException {
		// 拿到字节码对象
		// 1.Class.forName(类的路径);
		// Student.class
		Class clazz1 = Class.forName("day10.Student");
		// 2、类型.class
		Class clazz2 = Student.class;
		// 3、对象.getClass();
		Student student = new Student();
		Class clazz3 = student.getClass();
		
		System.out.println(clazz1 == clazz2);// true
		System.out.println(clazz2 == clazz3);// true
	}
	
	@Test
	public void testConstructor1() {
		// Student student = new Student();
		Class clazz = Student.class;
		Constructor[] constructors = clazz.getDeclaredConstructors();
		for (Constructor constructor : constructors) {
			System.out.println(constructor);
		}
	}
	
	@Test
	public void testConstructor2() {
		// Student student = new Student();
		Class clazz = Student.class;
		Constructor[] constructors = clazz.getConstructors();
		for (Constructor constructor : constructors) {
			System.out.println(constructor);
		}
	}
	
	@Test
	public void testConstructor3() throws Exception {
		Class clazz = Student.class;
		// private Student(String name) 
		Constructor constructor = clazz.getDeclaredConstructor(String.class);
		constructor.setAccessible(true);// 加上之后就可以访问私有的构造方法
		// Student student = new Student("张三")
		Student student = (Student) constructor.newInstance("张三");
		System.out.println(student);
		
		// java.lang.IllegalAccessException: Class day10.ReflectDemo can not access a member of class 
		// day10.Student with modifiers "private"
	}
	
	@Test
	public void testConstructor4() throws Exception {
		Class clazz = Student.class;
		// 得到无参构造方法
		Constructor constructor = clazz.getConstructor();
		Student student = (Student) constructor.newInstance();
		
		// 如果调用无参构造方法new对象，简化写法：
		Student stu = (Student) clazz.newInstance();
	}
	
	@Test
	public void testMethod1() throws Exception {
		Class clazz = Student.class;
		Student student = (Student) clazz.newInstance();
		Method method = clazz.getMethod("setName", String.class);
		// student.setName("张三");
		method.invoke(student, "张三");
		System.out.println(student);
	}
	
}
